package com.company.linkedList;

import java.util.Stack;

public class KthNodeOfList {


    public ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null||k<=0) {
            return null;
        }
//        return funByStack(head, k);
        return funByDoubleIndex(head,k);
    }

    private ListNode funByDoubleIndex(ListNode head,int k){
        int currentIndex=0;
        ListNode resultNode;

        ListNode node = head;
        resultNode = head;
        while (node!=null){
            currentIndex++;
            node=node.next;
            if(currentIndex<=k){
                continue;
            }
            resultNode= resultNode.next;
        }
        return resultNode;
    }
    private ListNode funByStack(ListNode head, int k){
        Stack<ListNode> stack = new Stack<>();
        ListNode node = head;
        while (node!=null){
            stack.push(node);
            node = node.next;
        }


        for (int i = 0; i < k; i++) {
           node= stack.pop();
        }
        return node;
    }
}
